<template>
  <drag-modal
    title="备份"
    :width="360"
    :visible="visible"
    :destroyOnClose="true"
    :confirmLoading="submitLoading"
    :maskClosable="false"
    @ok="ok"
    @cancel="cancel"
  >
    <a-spin :spinning="loading">
      <div class="modal-tool" v-if="treeData && treeData.length > 0">
        <a @click="checkAll">全选</a>
        <a-divider type="vertical" />
        <a @click="uncheckAll">取消全选</a>
      </div>
      <div style="max-height: 500px; overflow-y: auto;">
        <a-tree
          :tree-data="treeData"
          :show-icon="true"
          :show-line="false"
          :checkable="true"
          :selectable="false"
          :checkedKeys="checkedTreeNodeKeys"
          @check="onCheck"
        >
          <template slot="customTitle" slot-scope="item">
            <span><a-icon type="table" /> {{item.title}} </span>
          </template>
        </a-tree>
      </div>
    </a-spin>
  </drag-modal>
</template>

<script>
import {dataSourceService} from '@/services'

export default {
  name: 'BackupModal',
  props: {
    visible: {
      type: Boolean,
      required: true
    }
  },
  data () {
    return {
      loading: false,
      submitLoading: false,
      treeData: [],
      checkedTreeNodeKeys: []
    }
  },
  methods: {
    checkAll() {
      this.treeData.map((treeNode) => this.checkedTreeNodeKeys.push(treeNode.key))
    },
    uncheckAll() {
      this.checkedTreeNodeKeys = []
    },
    cancel() {
      this.$emit('cancel')
    },
    ok() {
      if (!this.checkedTreeNodeKeys || this.checkedTreeNodeKeys <= 0) {
        this.$message.warning('请选择要备份的表')
        return
      }
      this.submitLoading = true
      let checkedTreeNodeNames = []
      this.checkedTreeNodeKeys.forEach(key => {
        let index = this.treeData.findIndex(item => item.key === key)
        checkedTreeNodeNames.push(this.treeData[index].title)
      })
      const params = {
        ids: checkedTreeNodeNames
      }
      dataSourceService.backup(JSON.stringify(params)).then(res => {
        const result = res.data
        if (result.code === 200) {
          this.$emit('ok')
          this.$message.success(result.msg)
        }
      }).finally(this.submitLoading = false)
    },
    onCheck(checkedKeys, info) {
      this.checkedTreeNodeKeys = checkedKeys
    },
    queryAction(key) {
      this.loading = true
      this.treeData = []
      this.checkedTreeNodeKeys = []
      dataSourceService.queryTableTreeSelect().then(res => {
        const result = res.data
        if (result.code === 200 && result.data) {
          this.treeData = result.data
        }
      }).finally(this.loading = false)
    }
  }
}
</script>
<style lang="less" scoped>
  .ant-modal-body {
    padding: 12px 24px !important;
  }
  .modal-tool {
    padding: 0 8px;
    margin-bottom: 12px;
  }
</style>